package com.excilys.ptitwrap.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.excilys.ptitwrap.LocalWrapRecipeCreator;
import com.excilys.ptitwrap.R;
import com.excilys.ptitwrap.ViewHelper;
import com.excilys.ptitwrap.WrapRecipe;
import com.excilys.ptitwrap.WrapResource;
import com.excilys.ptitwrap.WrapResourceBuilder;

/**
 * An activity that let's the user input how many people are there to eat wraps,
 * and then delegates showing the result to {@link ShowRecipe} activity.
 * 
 * Also notice that this is the first activity on the stack.
 * 
 * @author Pierre-Yves Ricau
 * 
 */
public class LocalWrapInput extends Activity {

	private static final String				TAG						= LocalWrapInput.class.getSimpleName();

	private final LocalWrapRecipeCreator	wrapLocalRecipeCreator	= new LocalWrapRecipeCreator();

	private WrapResource					wrapResource;

	private EditText						smallEaters;
	private EditText						hungryEaters;
	private CheckBox						isGabrielEating;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		wrapResource = WrapResourceBuilder.build(this);

		setContentView(R.layout.local_wrap_input);

		findViews();

		addListeners();
	}

	/**
	 * Called when the Menu button is first pressed
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(R.string.menu_web_wrap) //
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						startActivity(new Intent(LocalWrapInput.this, WebWrap.class));
						return true;
					}
				});

		menu.add(R.string.menu_add_eater) //
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						startActivity(new Intent(LocalWrapInput.this, AddWrapEater.class));
						return true;
					}
				});

		menu.add(R.string.menu_remote_recipe) //
				.setOnMenuItemClickListener(new OnMenuItemClickListener() {
					@Override
					public boolean onMenuItemClick(MenuItem item) {
						retrieveRemoteRecipe();
						return true;
					}
				});
		return true;
	}

	/**
	 * Shows a progress dialog and loads the WrapRecipe from the server in a
	 * background thread. Will call {@link #retrieveRemoteFailed()} or
	 * {@link #startShowRecipeActivity(WrapRecipe)} depending on the result
	 */
	private void retrieveRemoteRecipe() {
		final ProgressDialog dialog = new ProgressDialog(this);
		dialog.setCancelable(false);
		dialog.setTitle(R.string.loading_remote_title);
		dialog.setMessage(getString(R.string.loading_remote_message));
		dialog.show();

		new AsyncTask<Void, Void, WrapRecipe>() {
			private RuntimeException	exception;

			@Override
			protected WrapRecipe doInBackground(Void... params) {
				try {
					return wrapResource.getRecipe();
				} catch (RuntimeException e) {
					Log.e(TAG, "An exception occured while retrieving the remote WrapRecipe", e);
					exception = e;
					return null;
				}
			}

			@Override
			protected void onPostExecute(WrapRecipe wrapRecipe) {
				dialog.cancel();
				if (exception != null) {
					retrieveRemoteFailed(exception);
				} else {
					startShowRecipeActivity(wrapRecipe);
				}
			}
		}.execute();
	}

	/**
	 * Showing error message when retrieving recipe failed
	 * 
	 * @param exception
	 */
	private void retrieveRemoteFailed(RuntimeException exception) {
		Toast.makeText(this, String.format(getString(R.string.loading_remote_failed), exception.getMessage()), Toast.LENGTH_LONG).show();
	}

	/**
	 * Adding listeners to view components
	 */
	private void addListeners() {
		findViewById(R.id.compute_wrap_recipe) //
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						computeWrapRecipe();
					}
				});
	}

	/**
	 * Retrieve view components from the inflated layout
	 */
	private void findViews() {
		smallEaters = (EditText) findViewById(R.id.small_eaters);
		hungryEaters = (EditText) findViewById(R.id.hungry_eaters);
		isGabrielEating = (CheckBox) findViewById(R.id.is_gabriel_eating);
	}

	/**
	 * Computes the number of wraps from the input fields, and computes the
	 * recipe and calls the next activity
	 */
	private void computeWrapRecipe() {

		int smallEatersNb = ViewHelper.inputAsInt(smallEaters);
		int hungryEatersNb = ViewHelper.inputAsInt(hungryEaters);

		int gabrielWraps = isGabrielEating.isChecked() ? 20 : 0;

		int numberOfWraps = 2 * smallEatersNb + 3 * hungryEatersNb + gabrielWraps;

		if (numberOfWraps == 0) {
			Toast.makeText(this, R.string.zero_wrap_eaters, Toast.LENGTH_LONG).show();
			return;
		}

		WrapRecipe wrapRecipe = wrapLocalRecipeCreator.computeRecipe(numberOfWraps);

		startShowRecipeActivity(wrapRecipe);
	}

	/**
	 * Starts the {@link ShowRecipe} activity
	 * 
	 * @param wrapRecipe
	 */
	private void startShowRecipeActivity(WrapRecipe wrapRecipe) {
		Intent showRecipeIntent = new Intent(this, ShowRecipe.class);
		showRecipeIntent.putExtra(ShowRecipe.WRAP_RECIPE_EXTRA, wrapRecipe);
		startActivity(showRecipeIntent);
	}

}